package vis.app.controller;

import java.util.Observable;

public class AppController extends Observable {
	public static final String CTRL_NONE = "CTRL_NO_ACTION";
	public static final String CTRL_INIT = "CTRL_INIT_DISPLAY";
	public static final String CTRL_RUN = "CTRL_RUN_DISPLAY";
	public static final String CTRL_PAUSE = "CTRL_PAUSE_DISPLAY";
	public static final String CTRL_RESUME = "CTRL_RESUME_DISPLAY";
	public static final String CTRL_STOP = "CTRL_STOP_DISPLAY";

	public static final String ACTION_PUSH = "ACTION_PUSH";
	public static final String ACTION_POP = "ACTION_POP";

	private static AppController _instance = null;

	private String visualItemName = "";
	private String sketchFullName = "";

	public static AppController getInstance() {
		if (null == _instance) {
			_instance = new AppController();
		}
		return _instance;
	}

	private EAppState state = EAppState.STATE_NONE;

	public EAppState getAppState() {
		return state;
	}

	public boolean isReady() {
		return EAppState.STATE_READY == state;
	}

	public boolean isPaused() {
		return EAppState.STATE_PAUSED == state;
	}

	public boolean isRunning() {
		return EAppState.STATE_RUNNING == state;
	}

	public boolean isFinished() {
		return EAppState.STATE_FINISHED == state;
	}

	public void toggleRunningPaused() {
		String actionControl = CTRL_NONE;
		if (isReady()) {
			actionControl = CTRL_RUN;
			state = EAppState.STATE_RUNNING;
		} else if (isRunning()) {
			actionControl = CTRL_PAUSE;
			state = EAppState.STATE_PAUSED;
		} else if (isPaused()) {
			actionControl = CTRL_RESUME;
			state = EAppState.STATE_RUNNING;
		}

		EventControl eventCtr = new EventControl(actionControl, visualItemName, sketchFullName);
		setChanged();
		notifyObservers(eventCtr);
	}

	public void setStateFinished() {
		EventControl eventCtr = new EventControl();

		if (isRunning() || isPaused()) {
			state = EAppState.STATE_FINISHED;
			eventCtr.actionControl = CTRL_STOP;
			System.out.println("SYSTEM IS NOW TERMINED");
		}

		eventCtr.visualItemName = visualItemName;
		eventCtr.sketchFullName = sketchFullName;
		setChanged();
		notifyObservers(eventCtr);
	}

	public void setStateReady() {
		state = EAppState.STATE_READY;
		System.out.println("SYSTEM IS NOW READY");
	}

	public void executeSketch(String visualItemName, String sketchFullName) {
		this.visualItemName = visualItemName;
		this.sketchFullName = sketchFullName;

		EventControl eventCtr = new EventControl(CTRL_INIT, visualItemName, sketchFullName);
		setChanged();
		notifyObservers(eventCtr);
	}

	public void dispatchAction(String action) {
		EventControl evt = new EventControl(action, "", "");
		setChanged();
		notifyObservers(evt);
	}
}